import codecs
import importlib
import os
import subprocess

from core.util import CodeUtil


def execute(exe_path):
    subprocess.Popen(exe_path)


# 返回配置数据
def load_cfg(path):
    cfg_data = None
    f = None
    try:
        f = codecs.open(path, 'r', 'utf-8')
        cfg_str = f.read()
        cfg_data = CodeUtil.json_decode(cfg_str.replace('\n', ''))
        f.close()
    except Exception as e:
        print(e)
    finally:
        if f is not None and f.closed is not True:
            f.close()
    return cfg_data


# 动态模块加载
def load_module(mod_name: str):
    module = importlib.import_module(mod_name)
    return module


# 加载属性
def load_attr(mod: str, attr_name: str):
    return getattr(mod, attr_name)


# 加载类
def load_class(mod_name, class_name):
    mod = load_module(mod_name)
    return load_attr(mod, class_name)


# 获取目录下指定类型文件列表
def list_files(dir_name: str, filter_type = 'file', ext = None):
    allList = os.listdir(dir_name)
    fileList = []
    for f in allList:
        if f.find('_') == 0:
            continue

        #只返回文件， 过滤文件夹
        if filter_type == 'file' and f.rfind('.') == -1:
            continue

        if f.rfind('.') > -1:
            fName = f[0:f.rfind('.')]
            eName = f[f.rfind('.'):]
        else:
            fName = f
            eName = ''
        if ext != None:
            if eName.lower() != ext.lower():
                continue
        fileList.append(fName)
    return fileList


# 获取对象数据类型的名称
def type_of(obj):
    return type(obj).__name__
